package tubesprogin4;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MudusDaemon implements Runnable {
    
    public static int CHECK_PERIOD = 10; // dalam detik
    
    public void run() {
        while(true) {
            FileOutputStream fos = null;
            
            try {
                
                File deletedLog = new File(ClientSettings.CLIENT_LOG_PATH, "deleted.log");
                fos = new FileOutputStream(deletedLog, true);  
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                //bandingkan log terakhir sinkronisasi dengan kondisi folder sekarang
                File curLog = ClientLogFile.createLogFile();
                File lastSyncLog = ClientLogFile.getLogFile("last_synchronized.log");
                String[][] arrdel = searchMissing(lastSyncLog, curLog);
                //save ke deleted file log
                ClientFileUtil.makeLogFile("deleted.log", true);
                File deleteLog = ClientLogFile.getLogFile("deleted.log");
                saveDelToLog(arrdel, deleteLog);
                System.out.println("selesai update delete log");
                Thread.sleep(CHECK_PERIOD * 1000);                
            } catch (IOException ex) {
                Logger.getLogger(MudusDaemon.class.getName()).log(Level.SEVERE, null, ex);
            } catch(InterruptedException ex) {
                Logger.getLogger(MudusDaemon.class.getName()).log(Level.SEVERE, null, ex);
            }finally {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(MudusDaemon.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    //mencari entry file yang ada di base, tapi tidak ada di checked
    protected String[][] searchMissing(File base, File checked) throws FileNotFoundException, IOException {
        Scanner baseScanner = new Scanner(base);
        ArrayList<String[]> baseEntry = new ArrayList<String[]>();
        Scanner checkedScanner = new Scanner(checked);
        ArrayList<String[]> checkedEntry = new ArrayList<String[]>();
        File deletedLogFile = new File(ClientSettings.CLIENT_LOG_PATH, "deleted.log");
        if(!deletedLogFile.exists()) {
            deletedLogFile.createNewFile();
        }
        Scanner deletedScanner = new Scanner(deletedLogFile);
        ArrayList<String[]> actualdelEntry = new ArrayList<String[]>();
        
        while(baseScanner.hasNextLine()) {
            String line = baseScanner.nextLine();
            String[] split = line.split("\\|");
            baseEntry.add(split);
        }
        while(checkedScanner.hasNextLine()) {
            String line = checkedScanner.nextLine();
            String[] split = line.split("\\|");
            checkedEntry.add(split);
        }
        while(deletedScanner.hasNextLine()) {
            String line = deletedScanner.nextLine();
            String[] split = line.split("\\|");
            actualdelEntry.add(split);
        }
        String[][] arrbase = new String[baseEntry.size()][4];
        arrbase = baseEntry.toArray(arrbase);
        String[][] arrchecked = new String[checkedEntry.size()][4];
        arrchecked = checkedEntry.toArray(arrchecked);
        String[][] arractualdel = new String[actualdelEntry.size()][5]; // nambah waktu delete
        arractualdel = actualdelEntry.toArray(arractualdel);
        ArrayList<String[]> deletedEntry = new ArrayList<String[]>();
        for(int i=0;i<baseEntry.size();i++) {     
            boolean found = false;
            for(int j=0;j<checkedEntry.size();j++) {
                if(arrbase[i][0].equals(arrchecked[j][0]) && 
                        arrbase[i][1].equals(arrchecked[j][1])) {                                        
                    found = true;
                }                
            }    
            if(!found) {
                
                int actualindex = -1;
                for(int k=0;k<actualdelEntry.size();k++) {                    
                    if(arrbase[i][0].equals(arractualdel[k][0]) && 
                            arrbase[i][1].equals(arractualdel[k][1])) {
                        // jika yang file di base entry-nya sudah ada di daftar yang kedelete                            
                        actualindex = k;
                        break;
                    }                       
                }
                if(actualindex == -1) {                    
                    deletedEntry.add(createInfoDel(arrbase[i]));                    
                }else{                               
                    deletedEntry.add(arractualdel[actualindex]);                    
                }
            }
        }
        String[][] arrdel = new String[deletedEntry.size()][4];
        arrdel = deletedEntry.toArray(arrdel);
        return arrdel;
    }
    
    
    protected String[] createInfoDel(String[] oriinfofile) {
        long curtime = System.currentTimeMillis();
        String[] ret = new String[oriinfofile.length + 1];
        System.arraycopy(oriinfofile, 0, ret, 0, oriinfofile.length);
        ret[ret.length-1] = curtime+"";
        return ret;
    }
    
    protected static void saveDelToLog(String[][] arrdel, File logfile) throws FileNotFoundException {                
        FileOutputStream fos = new FileOutputStream(logfile);   
        PrintStream ps = new PrintStream(fos);
        
        for(int i=0;i<arrdel.length;i++) {
            ps.println(arrdel[i][0]+"|"+arrdel[i][1]+"|"+arrdel[i][2]+"|"+arrdel[i][3] + "|" + arrdel[i][4]);
        }
        
        ps.close();
    }    
    
    public static void main(String[] args) {
        new Thread(new MudusDaemon()).start();
    }   
}
